package nl.windgazer.arachne.components.yql;

import nl.windgazer.arachne.services.yql.YQLConduit;
import nl.windgazer.arachne.services.yql.YQLGeoLocation;
import nl.windgazer.arachne.services.yql.YQLLocation;

import org.apache.tapestry5.BindingConstants;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.json.JSONArray;
import org.apache.tapestry5.json.JSONObject;

public class YQLGeoIPComparisonMap extends YQLIPComparisonMap {

	//Injects and Persists

	@Inject
	private YQLConduit _yc;

	//Properties and Parameters

	@Parameter(required = false, principal = false, defaultPrefix = BindingConstants.PROP, name = "places")
	private String _places = "Amsterdam, NL; Rotterdam, NL; Den Haag, NL; Utrecht, NL; Nijmegen, NL; Zwolle, NL; Groningen, NL; Leeuwarden, NL; Eindhoven, NL; Maastricht, NL";

	private YQLLocation[] baseLocations = null;

	//Components

	//Events

	//Other (check for business-logic, it should not remain here)

	@Override
	public YQLLocation[] getBaseLocations() {
		if (baseLocations==null) {
			baseLocations = getGeoLocations(_places);
		}
		return baseLocations;
	}

	public YQLLocation[] getGeoLocations(String locationString) {
		final StringBuilder geos = new StringBuilder();
		for (final String ip:locationString.split(";")) {
			if (geos.length() > 0) {
				geos.append(" OR ");
			}
			geos.append("text='");
			geos.append(ip.trim());
			geos.append('\'');
		}
		geos.insert(0, "SELECT name, centroid FROM geo.places WHERE ");
		final JSONObject locationq = _yc.jsonByQuery( geos.toString());
		System.out.println("++++++++" + geos.toString());
		final int count = locationq.getInt("count");
		if (count==0) {
			return null;
		}

		try {
			final JSONArray pa = locationq.getJSONObject("results").getJSONArray("place");
			final YQLLocation[] locations = new YQLLocation[pa.length()];
			for (int i = 0; i < pa.length(); i++) {
				final JSONObject location = pa.getJSONObject(i);
				locations[i] = new YQLGeoLocation(location);
			}
			return locations;
		} catch (RuntimeException re) {
			final JSONObject o = locationq.getJSONObject("results").getJSONObject("place");
			final YQLLocation[] locations = new YQLLocation[1];
			locations[0] = new YQLGeoLocation(o);
			return locations;
		}
	}

}
